package com.zhangtao.note.web;

import com.alibaba.fastjson.JSON;
import com.zhangtao.note.po.NoteType;
import com.zhangtao.note.po.User;
import com.zhangtao.note.service.NoteTypeService;
import com.zhangtao.note.util.JsonUtil;
import com.zhangtao.note.vo.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/type")
public class NoteTypeServlet extends HttpServlet {
    private NoteTypeService typeService = new NoteTypeService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置首页导航高亮
        req.setAttribute("menu_page", "type");
        //1.得到用户行为
        String actionName = req.getParameter("actionName");
        //2.判断用户行为
        if ("list".equals(actionName)){

            //查询类型列表
            typeList(req, resp);
        } else if ("delete".equals(actionName)) {

            //删除类型
            deleteType(req, resp);
        } else if ("addOrUpdate".equals(actionName)) {
            //添加或修改类型
            addOrUpdate(req, resp);
        }
    }

    //添加修改操作方法
    private void addOrUpdate(HttpServletRequest req, HttpServletResponse resp) {
        //1.获取参数
        String typeName = req.getParameter("typeName");
        String typeId = req.getParameter("typeId");
        //2.获得session中的user对象
        User user = (User) req.getSession().getAttribute("user");
        //3.调用service的更新方法
        ResultInfo<Integer>resultInfo = typeService.addOrUpdate(typeName, user.getUserId(), typeId);
        //4.转为json格式后给ajax
        JsonUtil.toJson(resp, resultInfo);
    }

    //删除类型方法
    private void deleteType(HttpServletRequest req, HttpServletResponse resp) {
        //1.接收参数（类型id）
        String typeId = req.getParameter("typeId");
        //2.调用service的操作方法
        ResultInfo<NoteType> resultInfo  = typeService.deleteType(typeId);
        //3.转json格式
        JsonUtil.toJson(resp , resultInfo);
    }


    /**
     * 查询类型列表
     * @param req
     * @param resp
     */
    private void typeList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取Session作用域设置的user对象
        User user = (User) req.getSession().getAttribute("user");
        // 2. 调用Service层的查询方法，查询当前登录用户的类型集合，返回集合
        List<NoteType> typeList = typeService.findTypeList(user.getUserId());
        // 3. 将类型列表设置到request请求域中
        req.setAttribute("typeList", typeList);
        // 4. 设置首页动态包含的页面值
        req.setAttribute("changePage","type/list.jsp");
        // 5. 请求转发跳转到index.jsp页面
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }
}
